package com.home.cca.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * 类型转化
 */
public class ConvertUtil {

    /**
     * list to map
     */
    public static <K, V> Map<K, V> listToMap(List<V> list, Function<V, K> function) {
        Map<K, V> map = new HashMap<>();
        if (list == null || list.isEmpty()) {
            return map;
        }
        for (V t : list) {
            map.put(function.apply(t), t);
        }
        return map;
    }

    /**
     * list to list map
     */
    public static <K, V> Map<K, List<V>> listToMaps(List<V> list, Function<V, K> function) {
        Map<K, List<V>> map = new HashMap<>();
        if (list == null || list.isEmpty()) {
            return map;
        }
        for (V t : list) {
            K key = function.apply(t);
            if (map.containsKey(key)) {
                map.get(key).add(t);
            } else {
                ArrayList<V> arrayList = new ArrayList<>();
                arrayList.add(t);
                map.put(key, arrayList);
            }
        }
        return map;
    }
}
